import 'dart:async';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/http/apis/common.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/models/bannerModel.dart';
import 'package:qgchat/http/models/followModel.dart';
import 'package:qgchat/http/models/recommendModel.dart';

class NominateBloc implements BlocBase {

  NominateBloc() {
    onRefresh();
  }

  /// 分页
  int _page = 1;

  /// 分页数
  int _limit = 6;

  /// 热门主播列表
  List<RecommendModel> hotlist = [];

  /// 轮播列表
  List<BannerModel> bannerlist = [];

  /// 关注列表
  List<FollowModel> followlist = [];

  // ##########  STREAMS  ##############

  /// 轮播stream
  StreamController<List<BannerModel>> _swiperController = StreamController.broadcast();
  Sink<List<BannerModel>> get _inSwiperList => _swiperController.sink;
  Stream<List<BannerModel>> get outSwiperList => _swiperController.stream;

  /// 我关注的主播stream
  StreamController<List<FollowModel>> _followController = StreamController.broadcast();
  Sink<List<FollowModel>> get _inFollowList => _followController.sink;
  Stream<List<FollowModel>> get outFollowList => _followController.stream;

  /// 主播推荐stream
  StreamController<List<RecommendModel>> _recommendController = StreamController.broadcast();
  Sink<List<RecommendModel>> get _inRecommendList => _recommendController.sink;
  Stream<List<RecommendModel>> get outRecommendList => _recommendController.stream;

  void dispose(){
    _swiperController.close();
    _followController.close();
    _recommendController.close();
  }

  // ##########  HANDLING  ##############

  /// 获取轮播列表数据
  Future getSwiperList() async {
    List<BannerModel> result = await CommonApis.adpicture();
    bannerlist = result;
    if (!_swiperController.isClosed) {
      _inSwiperList.add(result);
    }
  }

  /// 获取推荐主播列表数据
  Future getRecommendList() async {
    List<RecommendModel> result = await CommonApis.recommend(page: _page, limit: _limit);
    hotlist.addAll(result);
    if (!_recommendController.isClosed) {
      _inRecommendList.add(hotlist);
    }
  }

  /// 重新加载页面
  Future onRefresh() async {
    _page = 1;
    hotlist.clear();
    bannerlist.clear();
    followlist.clear();

    await getSwiperList();
    await getRecommendList();
  }

  /// 加载更多
  Future onLoad() async {
    _page++;
    await getRecommendList();
  }

}